#!/bin/bash

command_exists() {
	command -v "$@" > /dev/null 2>&1
}

user="$(id -un 2>/dev/null || true)"

sh_c='sh -c'
if [ "$user" != 'root' ]; then
    if command_exists sudo; then
        sh_c='sudo -E sh -c'
    elif command_exists su; then
        sh_c='su -c'
    else
        echo "Error: this installer needs the ability to run commands as root.We are unable to find either "sudo" or "su" available to make this happen."
        exit 1
    fi
fi

# 更新镜像源
source_address=$(sudo cat /etc/apt/sources.list | grep "deb " | awk 'NR==1{print}' | awk -F " " '{print $2}')
if [ $source_address == "http://archive.ubuntu.com/ubuntu" ];then
    $sh_c 'sed -e "s|http://archive.ubuntu.com|http://mirrors.ustc.edu.cn|g"\
    -e "s|http://security.ubuntu.com|http://mirrors.ustc.edu.cn/|g"\
    -i.bak /etc/apt/sources.list'
    $sh_c 'apt-get update'
fi

# docker
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
curl -s -L https://nvidia.github.io/libnvidia-container/experimental/$distribution/libnvidia-container.list | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
$sh_c 'apt-get update'
$sh_c 'apt-get install -y nvidia-container-toolkit'
$sh_c 'apt-get install -y docker.io'

cat <<EOF | sudo tee /etc/docker/daemon.json
{
"data-root": "/data/docker_home",
"log-driver": "json-file",
    "storage-driver": "overlay2",
    "runtimes": {
        "nvidia": {
            "path": "/usr/bin/nvidia-container-runtime",
            "runtimeArgs": []
        }
    }
}
EOF
$sh_c 'systemctl restart docker.service'

# CRI
# wget https://github.com/Mirantis/cri-dockerd/releases/download/v0.3.3/cri-dockerd_0.3.3.3-0.ubuntu-jammy_amd64.deb
$sh_c 'dpkg -i cri-dockerd_0.3.3.3-0.ubuntu-jammy_amd64.deb'
$sh_c 'systemctl daemon-reload'
$sh_c 'systemctl enable cri-docker.service'
$sh_c 'systemctl enable --now cri-docker.socket'

# --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.9 --network-plugin=cni --cni-bin-dir=/opt/cni/bin --cni-cache-dir=/var/lib/cni/cache --cni-conf-dir=/etc/cni/net.d
cat <<EOF | sudo tee /lib/systemd/system/cri-docker.service
[Unit]
Description=CRI Interface for Docker Application Container Engine
Documentation=https://docs.mirantis.com
After=network-online.target firewalld.service docker.service
Wants=network-online.target
Requires=cri-docker.socket

[Service]
Type=notify
ExecStart=/usr/bin/cri-dockerd --container-runtime-endpoint fd:// --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.9 --network-plugin=cni
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always

# Note that StartLimit* options were moved from "Service" to "Unit" in systemd 229.
# Both the old, and new location are accepted by systemd 229 and up, so using the old location
# to make them work for either version of systemd.
StartLimitBurst=3

# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd 230.
# Both the old, and new name are accepted by systemd 230 and up, so using the old name to make
# this option work for either version of systemd.
StartLimitInterval=60s

# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

# Comment TasksMax if your systemd version does not support it.
# Only systemd 226 and above support this option.
TasksMax=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF

$sh_c 'systemctl daemon-reload'
$sh_c 'systemctl restart cri-docker.service'

# iptables
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward=1 # better than modify /etc/sysctl.conf
EOF

$sh_c 'modprobe overlay'
$sh_c 'modprobe br_netfilter'
$sh_c 'sysctl --system'

$sh_c 'lsmod | grep br_netfilter'
$sh_c 'lsmod | grep overlay'
$sh_c 'sysctl net.bridge.bridge-nf-call-iptables net.bridge.bridge-nf-call-ip6tables net.ipv4.ip_forward'

# Disable Swap
$sh_c 'swapoff -a'
$sh_c 'sed -ri "/\sswap\s/s/^#?/#/" /etc/fstab'

# kubernetes
$sh_c 'apt-get install -y apt-transport-https ca-certificates curl nfs-common'
curl https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list
deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main
EOF
$sh_c 'apt-get update'
$sh_c 'apt-get install -y kubeadm=1.26.6-00 kubelet=1.26.6-00 kubectl=1.26.6-00'
read -p "是否部署 master 节点(0：否；1：是)?" is_master
if [ $is_master -eq 1 ];then
    $sh_c 'kubeadm init --image-repository="registry.aliyuncs.com/google_containers" --kubernetes-version=v1.26.6 --pod-network-cidr=10.244.0.0/16 --cri-socket=unix:///var/run/cri-dockerd.sock'

    # --control-plane-endpoint=192.168.0.231
    # --upload-certs

    mkdir -p $HOME/.kube
    sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
    sudo chown $(id -u):$(id -g) $HOME/.kube/config

    $sh_c 'kubectl apply -f kube-flannel.yml'
    # $sh_c 'kubectl apply -f calico.yaml'

    # --cri-socket=unix:///var/run/cri-dockerd.sock
    $sh_c 'kubeadm token create --print-join-command'
fi

# zsh
if [ ! -d ~/.oh-my-zsh ];then
    $sh_c 'apt-get install -y zsh git curl wget'
    sed -i 's/\r$//' install_zsh.sh
    sh install_zsh.sh
    # sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
fi
